import pdfplumber
from django.core.exceptions import ObjectDoesNotExist
from pytils.translit import slugify
from django.dispatch import receiver
from django.db.models.signals import post_save, pre_save, post_delete

from main.models import Book, Group


@receiver(post_save, sender=Book)
def add_volume_to_book(instance, **kwargs):
    """ Добавляем количество страниц для книги """

    if not isinstance(instance.volume, int):
        with pdfplumber.open(instance.file.path) as file:
            volume = len(file.pages)
            instance.volume = int(volume)
            instance.save()


@receiver(pre_save, sender=Book)
def add_slug_to_book(instance, **kwargs):
    """ Добавляем slug для книги """

    instance.slug = slugify(instance.title)


@receiver(pre_save, sender=Book)
def add_group_to_book(instance, **kwargs):
    """ Добавляем группу для книги """

    try:
        instance.group
    except ObjectDoesNotExist:
        instance.group = Group.objects.get(title='Не указана')

